<?php
declare(strict_types=1);

include_once './vendor/autoload.php';

use Swow\ChannelException;
use Swow\Coroutine;
use Swow\Channel;
use Swow\Signal;
use Swow\Sync\WaitReference;

$channel = new Channel();
Coroutine::run(static function () use ($channel): void {
    Signal::wait(Signal::INT);
    $channel->push("Terminated by SIGINT\n");
});
Coroutine::run(static function () use ($channel): void {
    Signal::wait(Signal::TERM);
    $channel->push("Terminated by SIGTERM\n");
});
Coroutine::run(static function () use ($channel): void {
    $wr = new WaitReference();
    for ($c = 0; $c < 3; $c++) {
        Coroutine::run(static function () use ($c, $wr): void {
            work3($c);
        });
    }
    $wr::wait($wr);
    $channel->push("All workers done\n");
});
echo "Wait...\n";
$timeout = 5;
try {
    echo $channel->pop($timeout * 1000);
} catch (ChannelException $exception) {
    echo sprintf("Timeout after %d seconds\n", $timeout);
}


function work3(int $id): void
{
    for ($n = 0; $n++ < 3;) {
        echo "Do something...\n";
        sleep(1);
        echo sprintf("Worker[%d] Task#%d done\n", $id, $n);
    }
    echo sprintf("Worker[%d] exit\n", $id);
}
